#include "McuUpdateWorker.h"
#include "Mcu.h"

McuUpdateWorker *McuUpdateWorker::getInstance()
{
    static McuUpdateWorker singleton{};
    return &singleton;
}

int McuUpdateWorker::loadMcuBinFile(QString path)
{
    QFile binFile(path);
    if(!binFile.open(QIODevice::ReadOnly)) {
        emit syncInfoSignal(tr("mcu升级失败，不能正常打开mcu bin文件"));
        return -1;
    }
    g_mcuIap.binData.clear();
    while(!binFile.atEnd()) {
        g_mcuIap.binData.append(binFile.readLine(512));
    }
    g_mcuIap.size = g_mcuIap.binData.size();
    if (g_mcuIap.size > 40960) {
        emit syncInfoSignal(tr("mcu升级失败，bin文件不能大于40KB"));
        return -1;
    }
    memcpy(g_mcuIap.binBuffer, (uint8_t*)g_mcuIap.binData.data(), g_mcuIap.binData.size() );
    g_mcuIap.crc = Mcu::getInstance()->calculateCrc(g_mcuIap.binBuffer, g_mcuIap.binData.size());
}

McuUpdateWorker::McuUpdateWorker()
{
    g_timer = new QTimer();
    QObject::connect(g_timer, &QTimer::timeout, this, &McuUpdateWorker::timeoutSlot);
    g_timer->setSingleShot(true);
}

void McuUpdateWorker::startEnterMcuUpdateSlot(QString path)
{
    loadMcuBinFile(path);
    Mcu::getInstance()->mainframeMcuUpdateJumpMessage();

    g_mcuIap.count = 0;
    g_timer->start(2000);/* 2秒后开始升级 */
}

void McuUpdateWorker::mcuUpdateRequestSlot()
{
    int32_t startIndex = 0;

    startIndex = g_mcuIap.count * MAX_DATA_LENGTH;
    qDebug()<<"request one frame: mcu--->";

    if (g_mcuIap.count > (g_mcuIap.size / MAX_DATA_LENGTH)) {
        qDebug()<<"update end";
        emit mcuUpdateCompleteSignal();
        Mcu::getInstance()->mainframeMcuUpdateStopMessage(g_mcuIap.size, g_mcuIap.crc);
    } else {
        qDebug()<<QString("response [%1] frame: --->mcu").arg(g_mcuIap.count);
        Mcu::getInstance()->mainframeMcuUpdateResponseMessage(&g_mcuIap.binBuffer[startIndex], MAX_DATA_LENGTH);
        g_mcuIap.count++;
    }
}

void McuUpdateWorker::timeoutSlot()
{
    Mcu::getInstance()->mainframeMcuUpdateStartMessage();
}
